package cpu.footprint.ui;

import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.AppXUtilDao;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.Active;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseFragment;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.DateUtils;
import cpu.footprint.util.DialogUtil;
import cpu.footprint.view.XListView;
import cpu.footprint.view.photo.TouchImageActivity;

/**
 * Created by Administrator on 2017/3/7.
 */
@ContentView(R.layout.fragment_active)
public class ActiveFragment extends BaseFragment implements XListView.IXListViewListener {
    private String TAG = "ActiveFragment";
    @ViewInject(R.id.title_back)
    public ImageView title_back;//点击弹出左侧滑
    @ViewInject(R.id.title_content)
    public TextView title_content;//标题栏内容
    @ViewInject(R.id.title_menu_text)
    public TextView title_menu_text;//标题栏文字功能
    @ViewInject(R.id.title_menu_image)
    public ImageView title_menu_image;//标题栏图形功能
    @ViewInject(R.id.listview_active)
    private XListView listview_active;
    @ViewInject(R.id.image_floatadd_active)
    private Button button_floatadd_active;//悬浮加号
    private CommonAdapter<Active> activeadapter;//群组适配器
    private List<Active> activeList = new ArrayList<>();
    private int startCount = 1;//页码
    private static int pagerCount = 8;// 每页显示多少条数据
    private boolean isHasMore = true;
    private AppXUtilDao mAppXUtilDao = new AppXUtilDao();
    private MyApplication myApplication;
    private User user = new User();
    private SpannableStringBuilder builder;
    private int screenWidth = 0;//屏幕宽度
    private int screenHeight = 0;//屏幕宽度
    private ForegroundColorSpan blackSpan;//ForegroundColorSpan 为文字前景色 ，BackgroundColorSpan为文字背景
    // private SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    //private SimpleDateFormat reshSdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    private Date reshDate = null;
    private Dialog mDialog;
    public LocationClient mLocationClient = null;
    private Boolean isclick = false;
    private int flag = 0;//(0:初始 无刷新无加载，1刷新 2加载更多)
    public BDLocationListener myListener = new MyLocationListener();
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {
                case ResultMessage.GET_ACTIVES_SUCCESS: {
                    String jsonStr = (String) msg.obj;
                    List<Active> list = JSON.parseArray(jsonStr,
                            Active.class);
                    if (list.size() < pagerCount) {
                        isHasMore = false;
                    } else {
                        isHasMore = true;
                    }
                    onLoad();
                    if (flag == 1 || flag == 0) {
                        activeList.clear();
                    } else if (flag == 2) {
                        listview_active.setSelection(startCount - pagerCount);
                    }
                    activeList.addAll(list);
                    initAdapter();
                    activeadapter.notifyDataSetChanged();
                }
                break;
                case ResultMessage.GET_ACTIVES_FAILED:
                    onLoad();
                    CreateDialogUtil.ToastShow(getActivity(), msg.obj.toString());
                    break;
                case ResultMessage.JOINACTIVE_SUCCESS: {
                    CreateDialogUtil.ToastShow(getActivity(), "加入活动成功！");
                }
                break;
                case ResultMessage.JOINACTIVE_FAILED: {
                    CreateDialogUtil.ToastShow(getActivity(), "加入活动失败！");
                }
                break;
                case ResultMessage.FAILED:
                    CreateDialogUtil.ToastShow(getActivity(), "连接失败");
                    break;
                case ResultMessage.TIMEOUT:
                    CreateDialogUtil.ToastShow(getActivity(), "连接超时");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        initViewAndLister(view);
        myApplication = (MyApplication) getActivity().getApplication();
        user = myApplication.getUser();
        initLocation();//初始化定位信息，显示当前城市名
        return view;
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        activeadapter = new CommonAdapter<Active>(getActivity(), activeList,
                R.layout.active_item) {
            @Override
            public void convert(ViewHolder helper, final Active item,
                                int position) {
                TextView text_join = helper.getView(R.id.text_join);
                if (myApplication.isLogin() && user != null && (user.getId() == item.getUser().getId() || user.getCurrentlyActiveId() == item.getUser().getId())) {
                    text_join.setEnabled(false);
                    text_join.setText("退出活动");
                    text_join.setTextColor(getResources().getColor(R.color.colorRed));
                }
                text_join.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (myApplication.isLogin()) {
                            user = myApplication.getUser();
                            if (user.getId() == item.getUser().getId() || user.getCurrentlyActiveId() == item.getUser().getId()) {
                                CreateDialogUtil.ToastShow(mContext, "您已经加入了该活动，不能重复加入...");
                            } else {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("mobilePhone", user.getMobilePhone());
                                map.put("token", user.getToken());
                                map.put("activeId", item.getId());
                                mAppXUtilDao.JoinActive(mHandler, map);
                                mDialog.show();
                            }
                        } else {
                            CreateDialogUtil.ToastShow(mContext, "请先登录...");
                        }
                    }
                });
                helper.setText(R.id.text_activeName, item.getName());
                helper.setText(R.id.text_activeTime, DateUtils.dateToString(item.getBeginTime(),true) + " - " + DateUtils.dateToString(item.getEndTime(),true));
                helper.setText(R.id.text_activitySite, item.getActivitySite());
                String description = item.getDescription();
                if (description != null) {
                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                    Matcher m = p.matcher(description);
                    description = m.replaceAll("");
                }
                helper.setText(R.id.text_description, "活动简介:" + description);
                TextView textView = helper.getView(R.id.text_description);
                builder = new SpannableStringBuilder(textView.getText().toString());
                blackSpan = new ForegroundColorSpan(Color.BLACK);
                builder.setSpan(blackSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.setText(builder);
                String imagePaths = item.getImagePaths();
                String[] imgPaths = imagePaths.split(";");
                ArrayList<String> imgArray = new ArrayList<>();
                for (int i = 0; i < imgPaths.length; i++) {
                    if (i >= 3) {
                        break;
                    }
                    imgArray.add(ApiUrl.URL_HOST + imgPaths[i]);
                }
                LinearLayout image_view = helper.getView(R.id.image_view);
                if (imgPaths.length > 0) {
                    image_view.setVisibility(View.VISIBLE);
                    ImageView[] imageViews = {helper.getView(R.id.img_1), helper.getView(R.id.img_2), helper.getView(R.id.img_3)};
                    for (int i = 0; i < imgPaths.length; i++) {
                        if (i >= 3) {
                            break;
                        }
                        Picasso.with(getActivity()).load(ApiUrl.URL_HOST + imgPaths[i]).placeholder(R.mipmap.defaultpicture).into(imageViews[i]);
                        setOnClick(imageViews[i], imgArray, i);
                    }
                } else {
                    image_view.setVisibility(View.GONE);
                }
            }
        };
        listview_active.setAdapter(activeadapter);
        activeadapter.notifyDataSetChanged();
    }

    /**
     * 对图片设置点击事件-实现查看大图
     *
     * @param view
     */
    private void setOnClick(ImageView view, final ArrayList<String> imgPaths, final int index) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TouchImageActivity.class);
                intent.putExtra("index", index);
                intent.putStringArrayListExtra("imgs", imgPaths);
                startActivity(intent);
                getActivity().overridePendingTransition(0, R.anim.fade);
            }
        });
    }

    /**
     * 初始化控件和监听
     *
     * @param view
     */
    private void initViewAndLister(final View view) {
        title_back.setImageResource(R.mipmap.menu);
        title_menu_text.setVisibility(View.VISIBLE);
        title_menu_text.setText("城市(全部)");
        title_menu_image.setVisibility(View.VISIBLE);
        title_menu_image.setImageResource(R.mipmap.triangle);
        title_content.setText("活动");
        mDialog = DialogUtil.getLoadDialog(getActivity(), "数据加载中...");
        listview_active.setPullLoadEnable(true);
        listview_active.setPullRefreshEnable(true);
        listview_active.setXListViewListener(this);
        listview_active.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Active active = activeList.get(position - 1);
                Intent intent = new Intent(getActivity(), ActiveDetailActivty.class);
                intent.putExtra("active", active);
                startActivityForResult(intent, 2);
                getActivity().overridePendingTransition(0, R.anim.fade);
            }
        });
        button_floatadd_active.setOnTouchListener(new View.OnTouchListener() {
            int lastX, lastY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int ea = event.getAction();
                switch (ea) {
                    case MotionEvent.ACTION_DOWN:
                        isclick = false;//当按下的时候设置isclick为false
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        isclick = true;//当按钮被移动的时候设置isclick为true
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        int l = v.getLeft() + dx;
                        int b = v.getBottom() + dy;
                        int r = v.getRight() + dx;
                        int t = v.getTop() + dy;
                        if (l < 50) {
                            l = 50;
                            r = l + v.getWidth();
                        }
                        if (t < 0) {
                            t = 0;
                            b = t + v.getHeight();
                        }
                        if (r > screenWidth - 100) {
                            r = screenWidth - 100;
                            l = r - v.getWidth();
                        }
                        if (b > screenHeight - 400) {
                            b = screenHeight - 400;
                            l = b - v.getHeight();
                        }
                        v.layout(l, t, r, b);
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        v.postInvalidate();
                        break;
                    default:
                        break;
                }
                return isclick;
            }
        });
    }

    /**
     * 请求数据
     */
    private void requestData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("from", startCount + "");
        map.put("pagerCount", pagerCount + "");
        if (title_menu_text.getText().toString().contains("全部")) {
            map.put("province", "");
        } else {
            map.put("province", title_menu_text.getText().toString());
        }
        APIService.Post(ApiUrl.URL_LIST_ACTIVE, map, new RespCallBack<BaseBean<Active>>(getActivity()) {
            @Override
            public void onSuccess(BaseBean<Active> result) {
                super.onSuccess(result);
                if (result.success) {
                    if (result.datas.size() < pagerCount) {
                        isHasMore = false;
                    } else {
                        isHasMore = true;
                    }
                    onLoad();
                    if (flag == 1 || flag == 0) {
                        activeList.clear();
                    } else if (flag == 2) {
                        listview_active.setSelection(startCount - pagerCount);
                    }
                    activeList.addAll(result.datas);
                    initAdapter();
                    activeadapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                if (mDialog != null && mDialog.isShowing())
                    mDialog.dismiss();
            }
        });
    }

    /*
     * 监听事件
     * @param v
     */
    @Event(value = {R.id.title_back, R.id.image_floatadd_active, R.id.title_menu_text, R.id.title_menu_image})
    private void OnClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                MainActivity activity = (MainActivity) getActivity();
                activity.leftNavChange();//侧滑栏状态切换
            }
            break;
            case R.id.image_floatadd_active: {
                //   Toast.makeText(getActivity(),"添加",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), CreateActiveActivity.class);
                startActivityForResult(intent, 2);
                getActivity().overridePendingTransition(0, R.anim.fade);
            }
            break;
            case R.id.title_menu_text: {
                Intent intent = new Intent(getActivity(), CityListActivity.class);
                startActivityForResult(intent, 1);
                getActivity().overridePendingTransition(0, R.anim.fade);
            }
            break;
            case R.id.title_menu_image: {
                Intent intent = new Intent(getActivity(), CityListActivity.class);
                startActivityForResult(intent, 1);
                getActivity().overridePendingTransition(0, R.anim.fade);
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == 1) {
            if (data != null) {
                String city = data.getStringExtra("city");
                title_menu_text.setText(city);
                requestData();
            }
        } else if (requestCode == 2 && resultCode == 2) {
            double activityLatitude = data.getDoubleExtra("activityLatitude", 0);
            double activityLongitude = data.getDoubleExtra("activityLongitude", 0);
            LatLng latLng = new LatLng(activityLatitude, activityLongitude);
            MainActivity.layout_map.performClick();
            MapFragment mapFragment = new MapFragment();
            Bundle bundle = new Bundle();
            bundle.putDouble("activityLatitude", activityLatitude);
            bundle.putDouble("activityLongitude", activityLongitude);
            mapFragment.setArguments(bundle);
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.otherFrameLayout, mapFragment);
            ft.addToBackStack(null);
            ft.commit();
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh() {
        flag = 1;
        startCount = 1;
        requestData();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (isHasMore) {
            startCount++;
            flag = 2;
            requestData();
        } else {
            listview_active.setSelection(activeList.size() - 1);
            listview_active.pauseLoadMore();//已经到底啦
        }
    }

    /**
     * 停止刷新
     */
    private void onLoad() {
        listview_active.stopRefresh();
        listview_active.stopLoadMore();
        reshDate = new Date();
        listview_active.setRefreshTime(DateUtils.dateToString(reshDate));
    }

    /**
     * 初始化位置
     */
    private void initLocation() {
        mLocationClient = new LocationClient(getActivity().getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        //就是这个方法设置为true，才能获取当前的位置信息
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("gcj02");//可选，默认gcj02，设置返回的定位结果坐标系
        //int span = 1000;
        //option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    @Override
    public void onPause() {
        System.out.println("--------active--onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        System.out.println("--------active--onStop");
        super.onStop();
    }

    @Override
    public void onStart() {
        System.out.println("--------active--onStart");
        super.onStart();
    }

    @Override
    public void onResume() {
        System.out.println("--------active--onResume");
        super.onResume();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            //经纬度
            double lati = location.getLatitude();
            double longa = location.getLongitude();
            //打印出当前位置
            Log.i("TAG", "location.getAddrStr()=" + location.getAddrStr());
            //打印出当前城市
            Log.i("TAG", "location.getCity()=" + location.getCity());
            title_menu_text.setText(location.getCity());
            mDialog.show();
            requestData();
            //返回码
            int i = location.getLocType();
        }
    }
}
